package com.example.baselibrary.widget;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import com.example.baselibrary.R;
import com.qmuiteam.qmui.link.QMUILinkTouchMovementMethod;

public class FixSpanTextView extends AppCompatTextView {

    /**
     * 记录当前 Touch 事件对应的点是不是点在了 span 上面
     */
    private boolean mTouchSpanHit;

    /**
     * 记录每次真正传入的press，每次更改mTouchSpanHint，需要再调用一次setPressed，确保press状态正确
     */
    private boolean mIsPressedRecord = false;
    /**
     * TextView是否应该消耗事件
     */
    private boolean mNeedForceEventToParent = false;

    private int highlightTextNormalColor;
    private int highlightTextPressedColor;
    private int highlightBgNormalColor;
    private int highlightBgPressedColor;

    public FixSpanTextView(Context context) {
        this(context, null);
    }

    public FixSpanTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        highlightTextNormalColor = ContextCompat.getColor(context, R.color.common_text);
        highlightTextPressedColor = ContextCompat.getColor(context, R.color.common_text);
        highlightBgNormalColor = Color.TRANSPARENT;
        highlightBgPressedColor = ContextCompat.getColor(context, R.color.bg_grey);
    }

    public FixSpanTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setHighlightColor(Color.TRANSPARENT);
    }

    public void setNeedForceEventToParent(boolean needForceEventToParent) {
        mNeedForceEventToParent = needForceEventToParent;
        setFocusable(!needForceEventToParent);
        setClickable(!needForceEventToParent);
        setLongClickable(!needForceEventToParent);
    }

    /**
     * 使用者主动调用
     */
    public void setMovementMethodDefault(){
        setMovementMethodCompat(QMUILinkTouchMovementMethod.getInstance());
    }

    public void setMovementMethodCompat(MovementMethod movement){
        setMovementMethod(movement);
        if(mNeedForceEventToParent){
            setNeedForceEventToParent(true);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!(getText() instanceof Spannable)) {
            return super.onTouchEvent(event);
        }
        mTouchSpanHit = true;
        // 调用super.onTouchEvent,会走到QMUILinkTouchMovementMethod
        // 会走到QMUILinkTouchMovementMethod#onTouchEvent会修改mTouchSpanHint
        boolean ret = super.onTouchEvent(event);
        if(mNeedForceEventToParent){
            return mTouchSpanHit;
        }
        return ret;
    }

    public void setTouchSpanHit(boolean hit) {
        if (mTouchSpanHit != hit) {
            mTouchSpanHit = hit;
            setPressed(mIsPressedRecord);
        }
    }

    @SuppressWarnings("SimplifiableIfStatement")
    @Override
    public boolean performClick() {
        if (!mTouchSpanHit && !mNeedForceEventToParent) {
            return super.performClick();
        }
        return false;
    }

    @SuppressWarnings("SimplifiableIfStatement")
    @Override
    public boolean performLongClick() {
        if (!mTouchSpanHit && !mNeedForceEventToParent) {
            return super.performLongClick();
        }
        return false;
    }

    @Override
    public final void setPressed(boolean pressed) {
        mIsPressedRecord = pressed;
        if (!mTouchSpanHit) {
            onSetPressed(pressed);
        }
    }

    protected void onSetPressed(boolean pressed) {
        super.setPressed(pressed);
    }

    public interface OnSpanTouchListener {
        void onSpanTouch(String spanText);
    }

    /**
     * @param text
     * @param spanText
     * @param listener
     */
    public void setSpanText(String text, String spanText, OnSpanTouchListener listener) {
        setSpanText(text, new String[]{spanText}, listener);
    }

    /**
     * @param text
     * @param spanTexts spanText 序列必须按照在text中的顺序组成
     * @param listeners
     */
    public void setSpanText(String text, String[] spanTexts, OnSpanTouchListener listeners) {
        SpannableString sp = new SpannableString(text);
        int start = 0;
        int index;
        int end;
        for (int i = 0; i < spanTexts.length; i++) {
            String spanText = spanTexts[i];
            index = text.indexOf(spanText, start);
            if (index == -1) {
                throw new IllegalArgumentException("text does not contain " + spanText);
            }
            end = index + spanText.length();
            final int position = i;
            sp.setSpan(new TouchSpan(highlightTextNormalColor, highlightTextPressedColor,
                    highlightBgNormalColor, highlightBgPressedColor) {
                @Override
                public void onSpanClick(View widget) {
                    if (listeners != null) {
                        listeners.onSpanTouch(spanTexts[position]);
                    }
                }
            }, index, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            start = end;
        }
        setText(sp);
    }


}
